package cn.car91.activity;

import java.util.List;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;
import android.widget.ViewFlipper;
import cn.car91.R;
import cn.car91.service.UpdateService;
import cn.car91.utils.RegexUtil;
import cn.car91.view.HeaderView;
import cn.car91.view.HerilyAlertDialog.Builder;
import cn.car91.view.MenuView;
import cn.car91.view.PageControlView;
import cn.car91.view.SliderMenu;

import com.lidroid.xutils.view.annotation.ViewInject;

public class MainFragmentActivity extends BaseFragmentActivity {
    public static final String naviAction = "item.change.broadcast.action";
	SharedPreferences sharedPreferences;
    SharedPreferences otherPreferences;

    String cityname;

    @ViewInject(R.id.menu)
    MenuView mMenuView;
    @ViewInject(R.id.area_select_text)
    Button areaBtn;
    @ViewInject(R.id.slider_menu)
    SliderMenu mSliderMenu;
    @ViewInject(R.id.navi_switcher)
    RadioGroup mSwitcher;
    @ViewInject(R.id.header)
    HeaderView headerView;
    /*@ViewInject(R.id.uiPagerView)
	AutoScrollViewPager uiViewPager;*/

    ViewFlipper viewFlipper;
    PageControlView pageControlView;

    List<View> uiViews;
    
    FragmentManager fm;
    
    MainActivity mainActivity;
    WashShopMainActivity washShopMainActivity;
    RepairShopMainActivity repairShopMainActivity;
    BoxMainActivity boxMainActivity;
    //MainCar91Activity mainCar91Activity;
    
    private boolean isSearch = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_fragment_main);
        super.onCreate(savedInstanceState);
        sharedPreferences = getCar91Application().getPlacePreferences();
        otherPreferences = getCar91Application().getOtherPreferences();

        String cname = sharedPreferences.getString("cityName", "");
        if (RegexUtil.isNotNull(cname)) {
            areaBtn.setText(cname);
        } else {
            areaBtn.setText(getResources().getString(R.string.view_header_area));
        }
        
        new Handler().postDelayed(new Runnable() {
            public void run() {
                if (!getCar91Application().isLocating()) {
                    new Builder(MainFragmentActivity.this).setMessage("网络环境较差，定位可能需花点时间").create().show();
                }
            }
        }, 8 * 1000);

        mSwitcher.setOnCheckedChangeListener(mCheckedChgLitener);
		/*DesUtils desUtil = new DesUtils(getCar91Application().getEncryptCode());
		try {
			LogUtils.e(desUtil.encrypt("111111"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
        fm = getSupportFragmentManager();

        mainActivity = new MainActivity();  
        washShopMainActivity = new WashShopMainActivity();
        repairShopMainActivity = new RepairShopMainActivity();
        boxMainActivity = new BoxMainActivity();
        
        try {
            FragmentTransaction transaction = fm.beginTransaction();  
            transaction.add(R.id.mian_fragment_content, mainActivity);  
            /*mainCar91Activity = new MainCar91Activity();
            transaction.add(R.id.mian_fragment_content, mainCar91Activity);  
            transaction.hide(mainCar91Activity);*/
            transaction.commit(); 
        } catch (Exception e) {
            // 返回时可能出现重复添加fragment
        }
        
        mSwitcher.check(R.id.navi_switcher_item_index);
        
        //registerReceiver(curNaviReceiver, new IntentFilter(SearchActivity.searchAction));
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };
    
    private void showFragment(Fragment fragment){
    	FragmentTransaction transaction = fm.beginTransaction();  
    	/*if(fragment!=mainActivity)
    		transaction.hide(mainActivity);
    	if(fragment!=mainCar91Activity)
    		transaction.hide(mainCar91Activity);
    	transaction.show(fragment);*/
        transaction.replace(R.id.mian_fragment_content, fragment);
    	
    	transaction.addToBackStack(null);
    	if(isSearch)
    		transaction.commitAllowingStateLoss();
    	else
    		transaction.commit();
    }

    OnCheckedChangeListener mCheckedChgLitener = new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
        	HeaderView headerView = (HeaderView) findViewById(R.id.header);
//        	Intent intent = new Intent();
//            intent.setAction(naviAction);
//            int cur = Item.CB_INDEX_index;
            switch (checkedId) {
                case R.id.navi_switcher_item_index:
//                    cur = Item.CB_INDEX_index;
                    showFragment(mainActivity);
                    try {
        				headerView.findViewById(R.id.area_select_text).setVisibility(View.GONE);
        			} catch (Exception e) {}
                    _showMapIco(false);
                    return;
                case R.id.navi_switcher_item_washshop:
//                    cur = Item.CB_INDEX_washshop;
//                    intent.putExtra("curItem", Item.CB_INDEX_washshop);
                    showFragment(washShopMainActivity);
                    _showMapIco(true);
                    break;
                case R.id.navi_switcher_item_repairshop:
//                    cur = Item.CB_INDEX_repairshop;
//                    intent.putExtra("curItem", Item.CB_INDEX_repairshop);
                    showFragment(repairShopMainActivity);
                    _showMapIco(true);
                    break;
                case R.id.navi_switcher_item_box:
//                    cur = Item.CB_INDEX_box;
//                    intent.putExtra("curItem", Item.CB_INDEX_box);
                    showFragment(boxMainActivity);
                    _showMapIco(false);
                    break;
//                case R.id.navi_switcher_item_around:
//                    cur = Item.CB_INDEX_around;
//                    intent.putExtra("curItem", Item.CB_INDEX_around);
//                    break;
//                case R.id.navi_switcher_item_exposure:
//                    cur = Item.CB_INDEX_exposure;
//                    intent.putExtra("curItem", Item.CB_INDEX_exposure);
//                    break;
             
            }
            /*mSliderMenu.setCanTouchScroll(false);
            mainCar91Activity.initSelect(cur);
            showFragment(mainCar91Activity);*/
            
            try {
      				headerView.findViewById(R.id.area_select_text).setVisibility(View.VISIBLE);
      			} catch (Exception e) { }
            
            //sendBroadcast(intent);
            /*Intent intent = new Intent(MainFragmentActivity.this, MainCar91Activity.class);
            intent.putExtra("car91_item", cur);
            startActivity(intent);*/
        }
    };
    
    private void _showMapIco(boolean show){
      if(show) {
        headerView.findViewById(R.id.imgBtn_search).setVisibility(View.GONE);
        headerView.findViewById(R.id.imgBtn_map).setVisibility(View.VISIBLE);
      } else {
        headerView.findViewById(R.id.imgBtn_map).setVisibility(View.GONE);
        headerView.findViewById(R.id.imgBtn_search).setVisibility(View.VISIBLE);
      }
    }

    boolean isExit;
    
    @Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
    	if (mSliderMenu.isOpen()) {
            mSliderMenu.closeMenu();
        } else {
        	if(mSwitcher.getCheckedRadioButtonId()==R.id.navi_switcher_item_index){
                if (!isExit) {
                    isExit = true;
                    Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    mHandler.sendEmptyMessageDelayed(0, 2000);
                } else {
                    UpdateService.isFirst = true;
                    Intent intent = new Intent();
                    intent.setAction(BaseActivity.exitAction);
                    sendBroadcast(intent);
                }
        	} else {
        		mSwitcher.check(R.id.navi_switcher_item_index);
        	}
        }
	}

    /*private BroadcastReceiver curNaviReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context arg0, Intent arg1) {
			isSearch=true;
			int item = arg1.getIntExtra("curItem", Item.CB_INDEX_repairshop);
			switch (item) {
	            case Item.CB_INDEX_index:
	            	mSwitcher.check(R.id.navi_switcher_item_index);
	                break;
	            case Item.CB_INDEX_washshop:
	            	mSwitcher.check(R.id.navi_switcher_item_washshop);
	                break;
	            case Item.CB_INDEX_repairshop:
	            	mSwitcher.check(R.id.navi_switcher_item_repairshop);
	                break;
	            case Item.CB_INDEX_box:
	            	mSwitcher.check(R.id.navi_switcher_item_box);
	                break;
	            
	        }
        }
	};*/

	@Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        try {
            try {
                unregisterReceiver(mMenuView.loginBroadcastReceiver);
            } catch (Exception e) {}
            //unregisterReceiver(curNaviReceiver);
        } catch (Exception e) {
        }finally{
        	UpdateService.isFirst = true;
        }
        super.onDestroy();
    }
}
